app.controller('deviceCtrl', function($rootScope, $scope, httpService, $timeout, toaster, wtmapService, $parse, $localStorage){
    $scope.RecordType = wtSys.Emun.RecordType;
    $scope.DeviceStatus = wtSys.Emun.DeviceStatus;//隐患状态
    $scope.searchList = [
        {
            "typeName" : "组别",
            "typeList" : [
                {"Id" : 1, "Name" : "网络组"},
                {"Id" : 2, "Name" : "动力组"},
            ]
        },
    ];


    $scope.devicelyrid = "devicelyrid";
    /**
     * 绘制定位点配置
     * @type {{layerid: string, 图层ID
      * symbolUrl: string 定位点图片Url }}
     */
    $scope.pointOption = {
        //layerid:图形图层id
        "layerid" : "locationLayer",
        "symbolUrl" : "/assets/img/Icons/聚焦框64.png",
        symbolStyle : {
            width : 34,
            height : 34,
            angle : 0,
            xOffset : 0,
            yOffset : 17

        }
    };

    /*==============设置选择设施位置信息 Begin=============================*/

    //设置选择设施位置信息
    $scope.isShowGetPosition = false;
    /**
     * 打开 选择设位置panel
     */
    $scope.openSetPositionPanel = function(){
        $scope.isShowGetPosition = true;
    }
    /**
     * 关闭 选择设位置panel
     */
    $scope.closeGetPositionPanel = function(){
        $scope.isShowGetPosition = false;
        // 获取被选中的点的数据
        $scope.deviceModel.Lng = $scope.selectedPosition.x;
        $scope.deviceModel.Lat = $scope.selectedPosition.y;

    }

    $scope.getPositionOption = {
        mapid : "getPosition",
        center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 600,
        showgdmap : false
    };
    //Edit状态默认被选中的点坐标
    $scope.selectedPosition = {x : 0, y : 0};
    /*==============设置选择设施位置信息 End=============================*/
    // 日期组件
    $scope.openDate = function($event, key){
        $event.preventDefault();
        $event.stopPropagation();
        if(key){
            $parse(key).assign($scope, true);
        }
    };
    // 初始化查询变量
    $scope.initParam = function(){
        $scope.deviceList = [];
        $scope.page = 1;
        $scope.busy = false;
        $scope.limit = 10;
        $scope.isGetDetailTag = true;//第一次默认加载第一条记录右侧信息
    }
    $scope.edit = function(Id, index){
        // 还原表单以及表单值
        $scope.deviceForm.$setPristine();
        if(Id || Id == 0){
            $scope.deviceId = Id;
            $scope.index = index;
            $scope.editModalTitle = "修改巡检点";
            $scope.getDeviceDetail($scope.deviceId);
        } else {
            $scope.deviceId = null;
            $scope.index = null;
            $scope.deviceModel = {
                "Name" : "",
                "Code" : "",
                "RFID" : "",
                "Lat" : 0,
                "Lng" : 0,
                "Addr" : "",
                "DeviceTypeId" : null,
                "Contact" : "",
                "Phone" : "",
                "StartAt" : "",
                "EndAt" : "",
                "Spec" : "",
                "UseDept" : "",
                "Ext" : "",
                "Imgs" : []
            }
            $scope.editModalTitle = "新增巡检点";
        }
        $('#editModal').modal('show');
    };
    //设施表单提交
    $scope.deviceFormSubmit = function(){
        $scope.deviceForm.$invalid = true;
        var path = "/device";
        var type = "POST";
        if($scope.deviceId){
            path = "/device/" + $scope.deviceId;
            type = "PUT";
        }
        httpService.request(type, path, $scope.deviceModel, function(result){
            $scope.deviceForm.$invalid = false;
            toaster.pop("success", "提示", result.message);
            $('#editModal').modal('hide');
            // 更新列表数据
            var arr = $scope.deviceList;
            if($scope.index != null && $scope.index >= 0){
                arr[$scope.index] = $scope.deviceModel;//index存在直接更新
                $scope.deviceDetailModel = angular.copy($scope.deviceModel);//更新右侧详情
            } else {
                arr.unshift(result.data);
                $scope.activeId = result.data.Id;
            }
            $scope.deviceList = arr;
        })
    }
    //删除设施弹框处理
    $scope.del = function(item, index){
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除设施
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = '/device/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.deviceList;
            arr.splice($scope.index, 1);
            $scope.deviceList = arr;
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
    //获取设施列表
    $scope.getDeviceList = function(isSearch){
        if(isSearch){
            $scope.initParam();
        }
        if($scope.busy) return false;
        var key = $scope.key ? $scope.key : "";
        var path = '/device?page=' + $scope.page + '&limit=' + $scope.limit + '&filter=key:' + key; // '/device?page=1&limit=40';
        $scope.busy = true;
        httpService.request("GET", path, null, function(result){
            $scope.count = result.count;
            //如果是过虑查询，清掉之前的地图数据
            if(isSearch)
                $scope.mapobj.drawApi.clearGraphics($scope.devicelyrid);
            angular.forEach(result.data, function(data, i){
                $scope.deviceList.push(data);
                // 绘制
                $scope.drawDevice(data);



            });
            if(result.data.length >= $scope.limit){
                $scope.busy = false;
                $scope.page += 1;
            }
            //搜索结果为空 将activeId置为空
            if($scope.deviceList.length == 0){
                $scope.activeId = null;
                return
            }
            if($scope.deviceList.length > 0 && $scope.isGetDetailTag){
                $scope.isGetDetailTag = false;
                var arr = $scope.deviceList;
                $scope.activeId = arr[0].Id;//默认查询第一条记录的详情
            }
        });
    }
    //获取设施详情
    $scope.getDeviceDetail = function(Id, isRgt){
        var path = '/device/' + Id;
        httpService.request("GET", path, null, function(result){
            if(isRgt){
                $scope.deviceDetailModel = result.data;
            } else {
                $scope.deviceModel = result.data;
            }
            $scope.deviceLocation();
        });
    }
    //获取设施类型
    $scope.getDeviceType = function(){
        var path = '/devicetype';
        httpService.request("GET", path, null, function(result){
            $scope.deviceTypeList = result.data;
        });
    }
    //获取右侧model
    $scope.getRgtModel = function(){
        //点击列表重置查询参数
        if(!$scope.activeId){
            return
        }
        $scope.getDeviceDetail($scope.activeId, true);//获取设施详情
        /*$scope.recordList = [];
         $scope.recordPage = 1;
         $scope.recordBusy = false;
         $scope.getRecordList();*/

    }
    //获取设施记录列表
    $scope.getRecordList = function(isSearch){
        if($scope.recordBusy) return false;
        var path = '/record?deviceid=' + $scope.activeId + '&page=' + $scope.recordPage + '&limit=' + $scope.limit;
        $scope.recordBusy = true;
        httpService.request("GET", path, null, function(result){
            angular.forEach(result.data, function(data, i){
                $scope.recordList.push(data);
            });
            if(result.data.length >= $scope.limit){
                $scope.recordBusy = false;
                $scope.recordPage += 1;
            }
        });
    }
    /**
     * 设施定位操作
     * @param id 传入设施id
     *
     */
    $scope.deviceLocation = function(){

        if($scope.mapobj){
            $scope.mapobj.drawApi.clearGraphics($scope.pointOption.layerid);
        }
        if($scope.deviceDetailModel && $scope.deviceDetailModel.Lng){
            $scope.mapobj.drawApi.drawPoint($scope.deviceDetailModel.Lng, $scope.deviceDetailModel.Lat, $scope.pointOption);
            $scope.mapobj.zoomTobyXY($scope.deviceDetailModel.Lng, $scope.deviceDetailModel.Lat, 15);
        } else {
            toaster.warning("提示", "您选择的设备还未进行定位!");
        }

    };
    //地图高度
    $scope.mapheight = ($(".rgt-wrap").height() - 85) || 700;

    $scope.mapService = wtmapService;
    // 地图初始化
    $scope.mapIntialed = function(scope){
        var promise = wtmapService.intialMap('map1', false, 0, $rootScope.arcgisConfig.lods); //同步调用，获取承诺接口

        promise.then(function(mapobj){

            //477419.175, 2816742.538

            //mapobj.addDynamicMap($rootScope.arcgisConfig.baseMap);

            //mapobj.drawApi.drawPoint(477419.175, 2816742.538);

            //mapobj.zoomTobyXY(477419.175, 2816742.538, 12);
            $scope.mapobj = mapobj;
            //获取设施列表
             $scope.getDeviceList();
        }, function(data){
            //调用承诺接口reject();
        });

    };

    //绘制图标
    $scope.drawDevice = function(dataitem){

        var img = "/assets/img/Icons/patron_巡查点32.png";


        var optionData = {
            "layerid" : $scope.devicelyrid,
            "symbolUrl" : img,
            "symbolStyle" : {"height" : 32, "width" : 32, "angle" : 0, xOffset : 0,
                yOffset : 16},
            "attributes" : dataitem
        };
        $scope.mapobj.drawApi.drawPoint(dataitem.Lng, dataitem.Lat, optionData);

        if(!$scope.devicelyr){
            $scope.devicelyr = $scope.mapobj.appMap.getLayer($scope.devicelyrid);
            $scope.devicelyr.on("click", function(e){
                $scope.leftDataLocation(e.graphic.attributes);
            });
        }

    };
    //点击图标定位左边数据
    $scope.leftDataLocation = function(dataItem){

        $scope.setCurrent(dataItem.Id);
        $scope.mapobj.drawApi.clearGraphics($scope.pointOption.layerid);
        $scope.mapobj.drawApi.drawPoint(dataItem.Lng, dataItem.Lat, $scope.pointOption);
    };

    $scope.setCurrent = function(id){
        $scope.activeId = id;
        $('.data-list').find('li').removeClass("active");//移除之前点击选中的class:active
        var activeEle = $('.data-list').find('li[relativeId="' + $scope.activeId + '"]');
        activeEle.addClass("active");

        $('.lft-wrap').scrollTop(0);
        var top = activeEle.position().top;


        $('.lft-wrap').scrollTop(top);

    }

    $scope.initParam();// 初始化查询列表变量
    $scope.getDeviceType();//获取设施分类
});
